package com.cwf.quality.common.strategy.filter;

import com.cwf.quality.common.enums.DataCheckFilterEnum;
import com.cwf.quality.model.dto.QualityResultInfo;
import com.cwf.quality.model.dto.datacheck.result.ValuePrefixCheckResult;
import com.cwf.quality.model.dto.datacheck.rule.CheckRuleInfo;
import com.cwf.quality.model.dto.datacheck.rule.DataCheckRuleInfo;
import com.cwf.quality.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ValuePrefixCheckFilter implements IDataCheckFilter {

    /**
     * 字段前缀校验
     *
     * @param dataCheckRuleInfo
     * @return
     */
    @Override
    public QualityResultInfo checkData(DataCheckRuleInfo dataCheckRuleInfo) {
        SqlUtils sqlUtils = dataCheckRuleInfo.getSqlUtils();
        Map<String, List<ValuePrefixCheckResult.ValuePrefixCount>> valuePrefixCountMap = new HashMap<>();


        List<CheckRuleInfo.ColumnPrefix> columnPrefixList = dataCheckRuleInfo.getCheckRuleInfo().getColumnPrefixList();
        for (CheckRuleInfo.ColumnPrefix columnPrefix : columnPrefixList) {
            String columnName = columnPrefix.getColumnName();
            String prefix = columnPrefix.getPrefix();

            String sql = DataCheckFilterEnum.VALUE_PREFIX_CHECK.getSql()
                    .replace("{table}", dataCheckRuleInfo.getTableName())
                    .replace("{column}", columnName)
                    .replace("{prefix}", prefix);

            List<Map<String, Object>> mapList = sqlUtils.query4List(sql, -1);

            List<ValuePrefixCheckResult.ValuePrefixCount> valuePrefixCountList = new ArrayList<>();
            for (Map<String, Object> map : mapList) {
                Object columnValue = map.get(columnName);
                Long count = (Long) map.get("not_prefix_count");
                valuePrefixCountList.add(new ValuePrefixCheckResult.ValuePrefixCount(columnValue, count));
            }
            valuePrefixCountMap.put(columnName, valuePrefixCountList);
        }
        QualityResultInfo qualityResultInfo = QualityResultInfo.builder()
                .code(0)
                .msg("成功")
                .result(new ValuePrefixCheckResult(valuePrefixCountMap))
                .build();
        return qualityResultInfo;
    }
}
